var express = require('express');
var router = express.Router();
var db = require("../db/db");
var custom = require("../services/apps/esb/custom");
var request = require("../services/apps/esb/request");

let handler = async function (req, res, next) {
	let startTime = new Date();
	console.log("---------------------",startTime)
	let error = function (status, msg, err) {
		if (err) {
			msg = msg + " 详细错误: " + err.name + " " + err.message;
		}
		err_data = { status: status, msg: msg };
		res.send(err_data);
		console.error(err_data, err);
	}
	let ok = function (result) {
		res.send({ status: 0, msg: "ok", data: result });
	}
	try {
		let interface = req.params.interface;
		let token = req.body.token;
		let data = req.body.data;
		let ip = req.ip.replace("::ffff:","");
		let sql = "select * from esb_interface where id=? and is_deleted=0";
		let result = await db.query(sql, [interface]);
		if(result.rows.length==0){
			error(500, "调用的接口ID不存在："+interface);
			return;
		}
		let ifrow=result.rows[0];
		let from_server=ifrow.from_server;
		let target_server=ifrow.target_server;
		let address=ifrow.address;

		sql = "select * from esb_server where id=? and is_deleted=0";
		result = await db.query(sql, [from_server]);
		if(result.rows.length==0){
			error(500, "调用服务器ID不存在："+from_server);
			return;
		}
		let fsrow=result.rows[0];
		let from_server_ip=fsrow.ip;
		let from_server_token=fsrow.token;

		if(token!=from_server_token){
			error(500, "调用服务器token错误："+token);
			return;
		}
		if(ip!=from_server_ip){
			error(500, "调用服务器ip错误："+from_server_ip+" "+ip);
			return;
		}

		sql = "select * from esb_server where id=? and is_deleted=0";
		result = await db.query(sql, [target_server]);
		if(result.rows.length==0){
			error(500, "目标服务器ID不存在："+target_server);
			return;
		}
		let tsrow=result.rows[0];
		let target_server_ip=tsrow.ip;
		let target_server_token=tsrow.token;
		
		if(address.indexOf("//"+target_server_ip+":")==-1 && address.indexOf("//"+target_server_ip+"/")==-1){
			error(500, "调用的接口地址与服务器IP不匹配："+address+" "+target_server_ip);
		}

		console.log("---esb info--- interface:" + interface + " ip:" + ip + " token:" + token + " address:" + address)

		let params={
			token: target_server_token,
			data: data
		}
		let log={
			interface_id: interface,
			request_report: JSON.stringify(data)
		}
		try{
			if(custom["i"+interface]){
				//客制调用
				result = await custom["i"+interface].call(address, params);
			}
			else{
				//常规调用
				result = await request.post(address, params);
			}
			let endTime = new Date();
			console.log("------------",result)
			//success log
			log.result="成功";
			log.return_report=JSON.stringify(result);
			log.time_take=endTime.getTime()-startTime.getTime();
			sql = "insert into esb_log set ?";
			await db.query(sql, [log]);
			ok(result);
		}
		catch (err) {			
			let endTime = new Date();
			//error log
			log.result="失败";
			log.result_detail=err.stack;
			log.time_take=endTime.getTime()-startTime.getTime();
			sql = "insert into esb_log set ?";
			await db.query(sql, [log]);
			error(500, "ESB的目标调用出现错误", err);
		}
	}
	catch (err) {
		error(500, "ESB调用出现错误", err);
	}
}
/* API. */
router.all('/interface/:interface', handler);

module.exports = router;
